package T2_10;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class T6 {
    public List<List<Integer>> threeSum(int[] nums) {
        //先将数组排序
        Arrays.sort(nums);
        int sum=0;
        //用于存放指定数组的值
        ArrayList<List<Integer>> list = new ArrayList<>();
        //遍历数组
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i]>0){
                return list;
            }
            if (i>0&&nums[i]==nums[i-1])continue;
            int head=i+1;
            int rear=nums.length-1;
            while (head<rear){
                sum=nums[i]+nums[head]+nums[rear];
                if (sum<0){
                    while(head<rear&&nums[head]==nums[++head]);
                } else if (sum > 0) {
                    while (head<rear&&nums[rear]==nums[--rear]);
                }else {
                    list.add(Arrays.asList(nums[i],nums[head],nums[rear]));
                    while(head<rear&&nums[head]==nums[++head]);
                    while(head<rear&&nums[rear]==nums[--rear]);
                }
            }
        }
        return list;
    }
}
